/* global window */
import modelExtend from 'dva-model-extend'
import { routerRedux } from 'dva/router'
import { message } from 'antd'
import { query, remove, genarationXML, downXMLFile } from 'services/report'
import { APIV4 } from 'utils/ip'
import queryString from 'query-string'
import { pageModel } from './common'

export default modelExtend(pageModel, {
  namespace: 'report',
  state: {
  },
  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/reports') {
          const payload = queryString.parse(location.search) || { page: 1 }
          dispatch({
            type: 'query',
            payload,
          })
        }
      })
    },
  },
  effects: {
    * query ({ payload = {} }, { call, put }) {
      const response = yield call(query, payload)
      const { code, msg, data } = response
      if (response && code === 0) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.total,
            },
          },
        })
      } else {
        throw { message: msg, code }
      }
    },
    * delete ({ payload = {} }, { call, put }) {
      const { code, data, msg } = yield call(remove, payload)
      if (code === 0) {
        message.success('successfully deleted!')
        yield put({
          type: 'report/query',
          payload,
        })
      } else {
        throw { message: msg, code }
      }
    },
    * generateXML ({ payload = {} }, { call, put }) {
      const { code, data, msg } = yield call(downXMLFile, payload)
      if (code === 0) {
        window.open(`${APIV4}/${data}`)
      } else {
        throw { message: msg || 'Network Error', code }
      }
    },
  },
})
